<script setup lang="ts">

import {onMounted, ref} from "vue";
import {centerMap, GETNOBASE} from "@/api";
import {registerMap, getMap, init, getInstanceByDom, EChartsType} from "echarts/core";
import { pinyin } from 'pinyin-pro'

import hehongcha from "@/assets/img/ecoProduce/hehongcha.png";
import hongyayu from "@/assets/img/ecoProduce/hongyayu.png";
import yanshantangfen from "@/assets/img/ecoProduce/yanshantangfen.png";
import maciguo from "@/assets/img/ecoProduce/maciguo.png";
import dengzhanguo from "@/assets/img/ecoProduce/dengzhanguo.png";
import yanshan from "@/assets/json/map/361124.json"
import * as echarts from "echarts";
import router from "@/router";

const code = ref("yanshan");
const option = ref({});
const centermapref = ref();
// 生态产品类型列表
const ncptype = ['河红茶', '红芽芋', '铅山烫粉', '麻糍粿', '灯盏稞'];
let myChart = ref();
const emit = defineEmits(["changestate"]);
let option1;

type RegionData = {
  name: string;
  value: any;
};
// 地图数据，包含不同地区的名称和对应的值（产品）
const mapdata = {
  'ncpsy': [
    // {name: "新滩乡", value: null},
    // {name: "河口镇", value: 0}, // 河红茶
    // {name: "稼轩乡", value: 3}, // 麻糍粿

    { name: "新滩乡", value: '' },
    { name: "永平镇", value: '红芽芋' },
    { name: "汪二镇", value: '' },
    { name: "葛仙山乡", value: '麻糍粿' },
    { name: "河口镇", value: '灯盏稞' },
    { name: "湖坊镇", value: '' },
    { name: "石塘镇", value: '' },
    { name: "稼轩乡", value: '' },
    { name: "紫溪乡", value: '铅山烫粉' },
    { name: "英将乡", value: '' },
    { name: "虹桥乡", value: '' },
    { name: "陈坊乡", value: '' },
    { name: "鹅湖镇", value: '' },
    { name: "天柱山乡", value: '' },
    { name: "武夷山镇", value: '河红茶' },
    { name: "太源畲族乡", value: '' },
  ]
}

// 散点图数据
const myData4 = [
  [               117.775339587,
    28.219849549000001, '红芽芋'], // 永平镇

  [              117.70813866699995,
    28.300720264000116, '灯盏稞'], // 河口镇
  [              117.77135635899999,
    28.045262198, '铅山烫粉'], // 紫溪乡

  [              117.618023274,
    28.100273932000001, '麻糍粿'], // 葛仙山乡
  [              117.85806315300001,
    27.982057802000001, '河红茶'], // 武夷山镇

];

const optionHandle = (regionCode: string,
                      list: RegionData[],
                      type: string,
) => {
  let top = 20;//
  let zoom = 1;
  let min1 = 0;
  let max1 = 0;
  let unit = "";
  let color1;
  let vM;
  let prex = "";
  const visualMap1 = {
    type: 'piecewise',
    left: 65,
    top: top,
    seriesIndex: 1,
    itemWidth: 66,
    itemHeight: 66,
    itemGap: 40, // 设置图例项之间的间距为 30px
    categories: ['河红茶', '红芽芋', '铅山烫粉', '麻糍粿', '灯盏稞'],
    itemSymbol: [`image://${hehongcha}`, `image://${hongyayu}`, `image://${yanshantangfen}`, `image://${maciguo}`, `image://${dengzhanguo}`],
    inRange: {
      // color: ['#f00', '#0f0', '#00f', '#ff0', '#0ff'], // ✅ 统一使用这个颜色
      symbolSize: {
        河红茶: 50, //地图中图标的大小
        红芽芋: 50,
        铅山烫粉: 50,
        麻糍粿: 50,
        灯盏稞: 50,
      },
      symbol: {
        河红茶: `image://${hehongcha}`,
        红芽芋: `image://${hongyayu}`,
        铅山烫粉: `image://${yanshantangfen}`,
        麻糍粿: `image://${maciguo}`,
        灯盏稞: `image://${dengzhanguo}`,
      }
    },
    textStyle: {
      color: "#ffffff",       // 字体颜色
      fontSize: 28,           // 字号
      fontFamily: "serif, Arial", // 字体 serif 优设标题黑
      // fontWeight: "bold"      // 加粗

    },
  };
  let scatter;
  if (type == "ncpsy") {
    vM = visualMap1;
    scatter = {
      type: 'scatter', // series图表类型
      coordinateSystem: 'geo', // series坐标系类型
      data: myData4,
    }
  }
  return {
    backgroundColor: "rgba(0,0,0,0)",
    tooltip: {
      show: false,
    },
    /* legend: { // 区域中心圆点
      show: false,
    }, */
    visualMap: vM,

    geo: {
      map: regionCode,
      selectedMode: false, //是否允许选中多个区域
      // 👇 增加以下参数控制地图位置和缩放
      left: '30%',   // 地图左边距离容器 5%
      right: '3%', // 地图右边留出空间，让地图整体左移，使图表靠右显示
      top: '1%',     // 距离顶部
      bottom: '2%',   // 距离底部
      zoom: zoom,    // 可适当放大地图以更好地填充右侧区域
      show: false,
    },
    series: [
      {
        name: "MAP",
        type: "map",
        map: regionCode, // 地图名 可以自定义
        data: list, // 数据
        selectedMode: false, //是否允许选中多个区域
        geoIndex: 1,
        // 👇 增加以下参数控制地图位置和缩放
        left: '30%',   // 地图左边距离容器 5%
        right: '3%', // 地图右边留出空间，让地图整体左移，使图表靠右显示
        top: '1%',     // 距离顶部
        bottom: '2%',   // 距离底部
        zoom: zoom,    // 可适当放大地图以更好地填充右侧区域
        // aspectScale: 0.9,
        tooltip: {
          show: true,
          formatter: function (params: any) {
            if (params.data) {
              if (params.data["value"] != '') {
                return params.name + "：" + prex + params.data["value"] + unit;
              } else {
                return params.name;
              }
            } else {
              return params.name;
            }
          },
          backgroundColor: "rgba(0,0,0,.6)",
          borderColor: "rgba(147, 235, 248, .8)",
          textStyle: {
            color: "#FFF",
          },
        },
        label: { // 显示标签， 例如地名
          show: true,
          color: "#fff",
          formatter: function (val: any) {
            if (val.data !== undefined) {
              return val.name.slice(0, 5);
            } else {
              return val.name.slice(0, 5);
            }
          },
          rich: {},
          textStyle: {
            color: "#fff",
            fontSize: 18,
          },
        },
        emphasis: { // 高亮状态下（区域获得鼠标焦点时可能触发高亮）的文本显示
          label: {
            show: false,
          },
          itemStyle: {
            // areaColor: "rgba(56,155,183,.7)",
            areaColor: { //渐变色 ， 中心， 半径，
              type: "radial",
              x: 0.5,
              y: 0.5,
              r: 0.8,
              colorStops: [
                {
                  offset: 0,
                  color: "rgba(147, 235, 248, 0)", // 0% 处的颜色
                },
                {
                  offset: 1,
                  color: "rgba(56,155,183, .8)", // 100% 处的颜色
                },
              ],
              globalCoord: false, // 缺为 false
            },
            borderWidth: 1,
          },
        },
        itemStyle: {
          borderColor: "rgb(15,208,230)",
          borderWidth: 1,
          // 默认状态下的区域颜色
          areaColor: { //渐变色 ， 中心， 半径，
            type: "radial",
            x: 0.5,
            y: 0.5,
            r: 0.8,
            colorStops: [
              {
                offset: 0,
                color: "rgba(22,213,239,0.3)", // 0% 处的颜色
              },
              {
                offset: 1,
                color: "rgba(56,155,183, .8)", // 100% 处的颜色
              },
            ],
            globalCoord: false, // 缺为 false
          },

          shadowColor: "rgba(128, 217, 248, .3)",
          shadowOffsetX: -2,
          shadowOffsetY: 2,
          shadowBlur: 10,

        },
      },
      {
        type: 'scatter', // series图表类型
        coordinateSystem: 'geo', // series坐标系类型
        data: myData4,
      },
    ],
  };
}

const dataSetHandle = async (regionCode: string, list: RegionData[], type: string) => {
  const geojson: any = await getGeojson(regionCode);
  console.log("geojson", geojson);
  let cityCenter: any = {};
  //获取当前地图每块行政区中心点
  geojson.features.forEach((element: any) => {
    cityCenter[element.properties.name] = element.properties.centroid || element.properties.center;
  });
  console.log("dataSetHandle");
  option.value = optionHandle(regionCode, list, type);//, max, min
  // option1 = optionHandle(regionCode, list, type);
  // myChart.setOption(option1);
  // myChart.on('datarangeselected', function (obj) {
  // 	console.log("hh")
  // })
};

const getData = async (regionCode: string, dataList: RegionData[], type: string) => {
  console.log("getData");
  dataSetHandle(regionCode, dataList, type);

  // var chart = this.$refs.centerMapRef;
  // var chartInstance = getInstanceByDom(chart as HTMLElement);

};
const getGeojson2 = (regionCode: string) => {
  return new Promise<boolean>(async (resolve) => {
    let mapjson = getMap(regionCode);
    mapjson = await GETNOBASE(`http://localhost:8123/map-geojson/${regionCode}.json`).then((data) => data);
    code.value = regionCode;
    registerMap(regionCode, {
      geoJSON: mapjson as any,
      specialAreas: {},
    });
    resolve(mapjson);
  });
};

const getGeojson = (regionCode: string) => {
  return new Promise<any>((resolve) => {
    // 从本地 assets 目录导入 json 文件
    import('@/assets/json/map/361124_18.json').then((mod) => {
      const mapjson = mod.default; // 注意这里使用 .default 获取实际内容
      code.value = regionCode;
      registerMap(regionCode, {
        geoJSON: mapjson,
        specialAreas: {},
      });
      resolve(mapjson);
    }).catch((err) => {
      console.error(`加载地图文件失败: ${regionCode}.json`, err);
      ElMessage.error(`加载地图失败，请检查文件是否存在`);
      resolve(null);
    });
  });
};


getData(code.value, mapdata['ncpsy'], "ncpsy");
const mapClick = (params: any) => {

  // console.log(params);
  if (params.componentSubType === "scatter") {
    // 示例：根据散点数据中的内容跳转到指定路径
    let productName = params.value[2]; // 获取散点图中对应的产品名称
    console.log(productName);
    const pinyinName = pinyin(productName, { toneType: 'none', nonZh: 'consecutive', separator: '' }); // 转换为拼音，无声调且无空格
    console.log('原始名称:', productName);
    console.log('拼音名称:', pinyinName); // 输出: hehongcha

    // 判断是否是特定产品名称
    if (['maciguo', 'hongyayu', 'yanshantangfen', 'dengzhanke'].includes(pinyinName)) {
      router.push(`/ecoProduce/product01`);
      console.log('跳转链接: /ecoProduce/product01');
    } else if (['sizhi', 'hunaggangshan', 'hehongcha'].includes(pinyinName)) {
      router.push(`/ecoProduce/product02`);
      console.log('跳转链接: /ecoProduce/product02');
    } else if (['gexianshan', 'mingqingguzhen', 'taiyaunshezu'].includes(pinyinName)) {
      router.push(`/ecoProduce/product03`);
      console.log('跳转链接: /ecoProduce/product03');
    } else {
      router.push(`/product/detail/${pinyinName}`);
      console.log('跳转链接: /product/detail/${pinyinName}');
    }


    // router.push(`/product/detail/${pinyinName}`);
    // window.open(`http://longbhu.com/product-detail?name=${productName}`, '_blank');

  }
}

const visualMapClick = (params: any) => {
  let visualMapSelected = params.selected;
  let i = 0;
  for (i = 0; i < ncptype.length; i++) {
    if (visualMapSelected[ncptype[i]] == false) {
      emit('changestate', ncptype[i]);
      visualMapSelected[ncptype[i]] = true;
      break;
    }
  }
  if (i < ncptype.length) {
    myChart.value.chart.dispatchAction({ //* 调用action方法将图例重新设置为全部选中
      type: 'selectDataRange',
      selected: visualMapSelected,
    })
  }

}



onMounted(() => {
  // setTimeout(() => {
  //   const chartDom = document.getElementById('ncpsy-chart')!;
  //   myChart.value = echarts.init(chartDom);
  //
  //   if (JSON.stringify(option.value) !== '{}') {
  //     myChart.value.setOption(option.value);
  //
  //   }
  // }, 200);
});
</script>

<template>
<!--  <router-view></router-view> &lt;!&ndash; ⚠️ 必须存在这一行 &ndash;&gt;-->
  <div class="ncpsy-left">
    <div class="ncpsy-left-main" id="ncpsy-chart1" ref="centermapref">
      <v-chart id="ncpsy-chart" class="chart" :option="option" @click="mapClick" autoresize
               @datarangeselected="visualMapClick" ref="myChart" v-if="JSON.stringify(option) != '{}'"/>
    </div>

  </div>
</template>


<style scoped lang="scss">
.ncpsy-left {
  height: 100%;
  width: 100%;
  padding-top: 25px;
  padding-bottom: 25px;

}

.ncpsy-left-main {
  height: 100%;
  width: 100%;

}
</style>
